package com.example.saifly.mainPage;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Fragment;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.Model.DailyPlanBg;
import com.example.saifly.Pop.PopNursingActivity;
import com.example.saifly.R;
import com.example.saifly.mainPage.home.HomeFragment;
import com.example.saifly.mainPage.plan.PlanFragment;
import com.example.saifly.mainPage.record.RecordFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class MainPageActivity extends Activity {

    private BottomNavigationView bottomNavigationView;
    private TextView plan_last_tile;
    private SharedPreferences sp= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

    List<Fragment> listFragment=new ArrayList<>();
    List<DailyPlanBg> dailyPlanBgList;          //后端发送过来的每日计划list

    private boolean isFirstFocus=true;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Intent home=new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
        return false;
    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//
//    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                sp.edit().putString("nextPlanContext","暂无")
                        .putString("nextPlanTime","暂无")
                        .apply();
                GetDailyPlan(sp.getString("uid","110"),new Date().getTime());
            }
        }).start();
    }

    @Override
    protected int getContentLayoutId() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        super.init();
        Intent intent=getIntent();
        initTab();
        dailyPlanBgList = new ArrayList<>();

        sp.edit().putString("planContext","全部完成").apply();
        sp.edit().putString("planTime","无执行时间").apply();

    }


    private void initTab(){
        ViewPager viewPager;

        bottomNavigationView=findViewById(R.id.main_tab);
        viewPager=findViewById(R.id.main_viewpager);
        PlanFragment planFragment=new PlanFragment();

        listFragment.add(planFragment);
        listFragment.add(new RecordFragment());
        listFragment.add(new HomeFragment());

        ViewPagerAdapter viewPagerAdapter=new ViewPagerAdapter(getSupportFragmentManager(),this,listFragment);
        viewPager.setAdapter(viewPagerAdapter);


        bottomNavigationView.setOnNavigationItemSelectedListener(menuItem -> {
            int itemId=menuItem.getItemId();
            switch (itemId){
                case R.id.main_tab_1:
                    viewPager.setCurrentItem(0);
                    return true;
                case R.id.main_tab_2:
                    viewPager.setCurrentItem(1);
                    return true;
                case R.id.main_tab_3:
                    viewPager.setCurrentItem(2);
                    return true;
                default:
                    break;
            }
            return false;
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                bottomNavigationView.getMenu().getItem(position).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    class ViewPagerAdapter extends FragmentStatePagerAdapter {
        List<Fragment> listFragment;
        Context context;

        public ViewPagerAdapter(@NonNull FragmentManager fm,Context context,List<Fragment> listFragment) {
            super(fm);
            this.context=context;
            this.listFragment=listFragment;
        }

        @NonNull
        @Override
        public androidx.fragment.app.Fragment getItem(int position) {
            return listFragment.get(position);
        }

        @Override
        public int getCount() {
            return listFragment.size();
        }
    }

    //从后端获取今日计划
    private interface ApiGetDailyPlan{
        @Headers({"Content-Type:application/json"})                             //大家都不变
        @POST("/arrange/getDailyPlan")                                          //后端给的路径
        Call<ResponseBody> GetDailyPlan(@Body JSONObject jsonObject);
    }

    private void GetDailyPlan(String patientPhone,Long date){
        //如果是患者家属就不需要进入录入医嘱页面
        if(sp.getString("identity","patient").equals("family")) return ;
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDailyPlan apiGetDailyPlan = retrofit.create(ApiGetDailyPlan.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",date);

        Call<ResponseBody> call = apiGetDailyPlan.GetDailyPlan(jsonObject);
        final Response<ResponseBody> response;
        try{
            response = call.execute();
            if(response.body() != null){
                JSONObject resultJson= JSON.parseObject(response.body().string());
                if(resultJson.getInteger("code")!=null&&resultJson.getInteger("code")==1){
                    String result  = resultJson.get("result").toString();
                    String resultDP = JSON.parseObject(result).get("dailyPlans").toString();
                    dailyPlanBgList = JSONObject.parseArray(resultDP,DailyPlanBg.class);
                    if(dailyPlanBgList == null || dailyPlanBgList.size() == 0){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(MainPageActivity.this, PopNursingActivity.class));
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}